<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关属性" type="warning" :closable="false" show-icon></el-alert>
      <el-row class="cate-opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader v-model="selectedKeys" :props="cateProps" :options="cateList" @change="handleChange"></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showDialog()">添加参数</el-button>
          <el-table :data="manyDataList" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="index" v-for="(item,index) in scope.row.attr_vals" closable @close="deleteTag(index,scope.row)">
                  {{item}}
                </el-tag>
                <el-input v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)" class="tag-input">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParam(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showDialog()">添加属性</el-button>
          <el-table :data="onlyDataList" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="index" v-for="(item,index) in scope.row.attr_vals" closable @close="deleteTag(index,scope.row)">
                  {{item}}
                </el-tag>
                <el-input v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)" class="tag-input">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.attr_id)">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParam(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <!-- 动态属性和静态属性公用同一个对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="30%" @close="addDialogClose()">
      <el-form :model="addForm" ref="addFormRef" label-width="100px">
        <el-form-item label="参数名称：" prop="attr_name">
          <el-input type="text" v-model="addForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑对话框 -->
    <el-dialog :title="'编辑' + titleText" :visible.sync="editDialogVisible" width="30%" @close="editDialogClose()">
      <el-form :model="editForm" ref="editFormRef" label-width="100px">
        <el-form-item label="参数名称：" prop="attr_name">
          <el-input type="text" v-model="editForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  categoriesList,
  attr,
  addCategory,
  delCategory,
  tagCategory,
  loadCategory,
  editCategory,
} from "@/request/api";
import { ElForm } from "element-ui/types/form";
import { ElInput } from "element-ui/types/input";
// 属性接口
interface attrProp {
  attr_id: number;
  attr_name: string;
  attr_sel: string;
  attr_vals: Array<string>;
  attr_write: string;
  cat_id: number;
  delete_time: number;
  inputVisible: boolean;
  inputValue: string;
}
// 类型接口
interface cateProp {
  attr_id: number;
  attr_name: string;
  attr_sel: string;
  attr_vals: string;
  attr_write: string;
  cat_id: number;
  delete_time: number;
}
interface rowProp {
  attr_id: number;
  attr_name: string;
  attr_sel: string;
  attr_vals: string;
  attr_write: string;
  cat_id: number;
}
import Vue from "vue";
import { Component, Ref } from "vue-property-decorator";
@Component
export default class Params extends Vue {
  cateList: [] = [];
  selectedKeys: Array<number> = [];
  cateProps: {
    value: string;
    label: string;
    children: string;
  } = {
    value: "cat_id",
    label: "cat_name",
    children: "children",
  };
  activeName: string = "many";
  manyDataList: Array<attrProp> = [];
  onlyDataList: Array<attrProp> = [];
  // 添加对话框的显示与隐藏
  addDialogVisible: boolean = false;
  addForm: {
    attr_name: string;
  } = { attr_name: "" };
  // 编辑对话框
  editDialogVisible: boolean = false;
  editForm: rowProp = {
    attr_id: 0,
    attr_name: "",
    attr_sel: "",
    attr_vals: "",
    attr_write: "",
    cat_id: 0,
  };
  created() {
    this.getCateList();
  }
  // 获取商品分类列表
  async getCateList() {
    const { data, meta } = await categoriesList();
    if (meta.status !== 200) return;
    this.cateList = data;
  }
  async getParamsList() {
    if (this.selectedKeys.length < 3) {
      this.selectedKeys = [];
      return;
    }
    const { data, meta } = await attr(this.getCateId, this.activeName);
    if (meta.status !== 200) return this.$message.error("获取数据列表失败");
    let target: Array<attrProp> = [];
    data.forEach((item: cateProp) => {
      target.push({
        ...item,
        attr_vals: item.attr_vals.trim() ? item.attr_vals.split(",") : [],
        // 给每一行的数据添加属性
        inputVisible: false,
        inputValue: "",
      });
    });
    if (this.activeName === "many") {
      this.manyDataList = target;
    } else {
      this.onlyDataList = target;
    }
  }
  handleChange() {
    this.getParamsList();
  }
  handleTabClick() {
    this.getParamsList();
  }
  // 显示添加对话框
  showDialog() {
    this.addDialogVisible = true;
  }
  // 添加属性
  async addParams() {
    const { data, meta } = await addCategory(this.getCateId, {
      attr_name: this.addForm.attr_name,
      attr_sel: this.activeName,
    });
    if (meta.status !== 201) return this.$message.error("添加参数失败");
    this.$message.success("添加成功");
    this.getParamsList();
    this.addDialogVisible = false;
  }
  @Ref("addFormRef") addFormRef!: ElForm;
  // 监听添加对话框关闭事件
  addDialogClose() {
    this.addFormRef.resetFields();
  }
  async editDialog(id: number) {
    const { data, meta } = await loadCategory(this.getCateId, id);
    if (meta.status !== 200) return;
    this.editDialogVisible = true;
    this.editForm = data;
  }
  @Ref("editFormRef") editFormRef!: ElForm;
  editDialogClose() {
    this.editFormRef.resetFields();
  }
  // 修改属性
  async editParams() {
    const { data, meta } = await editCategory(
      this.getCateId,
      this.editForm.attr_id,
      { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
    );
    if (meta.status !== 200) return this.$message.error("修改数据失败");
    this.$message.success("更新数据成功");
    this.editDialogVisible = false;
    this.getParamsList();
  }
  // 删除参数
  async removeParam(id: number) {
    const confirmRes = await this.$confirm(
      "此操作将永久删除该参数, 是否继续?",
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    ).catch((err) => {
      return err;
    });
    if (confirmRes !== "confirm") return this.$message.error("取消了删除操作");
    const { data, meta } = await delCategory(this.getCateId, id);
    if (meta.status !== 200) return this.$message.error("删除失败");
    this.$message.success("删除成功");
    this.getParamsList();
  }
  // 添加/删除tag项
  async optionTag(row: attrProp) {
    const { data, meta } = await tagCategory(this.getCateId, row.attr_id, {
      attr_name: row.attr_name,
      attr_sel: row.attr_sel,
      attr_vals: row.attr_vals.join(","),
    });
    if (meta.status !== 200) return this.$message.error("修改参数项失败");
    this.$message.success("修改参数项成功");
  }
  // 按回车键或者失去焦点触发的事件
  handleInputConfirm(row: attrProp) {
    if (row.inputValue.trim().length === 0) {
      row.inputValue = "";
      row.inputVisible = false;
      return;
    }
    row.attr_vals.push(row.inputValue.trim());
    row.inputValue = "";
    row.inputVisible = false;
    this.optionTag(row);
    // this.getParamsList()
  }
  @Ref("saveTagInput") saveTagInput!: ElInput;
  // 显示输入框
  showInput(row: attrProp) {
    // 显示输入文本框
    row.inputVisible = true;
    // 自动获取焦点
    this.$nextTick(() => {
      this.saveTagInput.focus();
    });
    console.log(row);
  }
  // 删除tag项
  deleteTag(index: number, row: attrProp) {
    row.attr_vals.splice(index, 1);
    this.optionTag(row);
  }
  get isBtnDisabled() {
    if (this.selectedKeys.length !== 3) {
      return true;
    }
    return false;
  }
  get getCateId() {
    if (this.selectedKeys.length === 3) {
      return this.selectedKeys[2];
    }
    return 0;
  }
  get titleText() {
    if (this.activeName === "many") {
      return "动态参数";
    }
    return "静态属性";
  }
}
</script>

<style lang="less" scoped>
.cate-opt {
  margin: 15px 0;
}
.el-tag {
  margin: 0 10px;
}
.tag-input {
  width: 120px;
}
</style>